package com.wanggsx.library.base.mvp;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 *  Created by {wanggsx} on 2017/4/19
 */
public abstract class BaseMainFragment extends Fragment implements IView {
    private View mRootView;
    private Unbinder unbinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getActivity().getWindow().setDimAmount(0);
        super.onCreate(savedInstanceState);
    }

    /** 延迟加载时间,单位毫秒 */
    protected int lazyLoadViewDelayTime(){
        return 0;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (mRootView == null){
            mRootView = getViewLayout(inflater, container, savedInstanceState);
        }
        if (lazyLoadViewDelayTime() > 0) {
            mRootView.setAlpha(0f);
            mRootView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mRootView.setAlpha(1.0f);
                }
            },lazyLoadViewDelayTime());
        }
        unbinder = ButterKnife.bind(this,mRootView);
        initData(mRootView, savedInstanceState);
        return mRootView;
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusMessage message) {
        busMessage(message);
    }


    protected abstract View getViewLayout(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);


    protected abstract void initData(View viewLayout, Bundle savedInstanceState);

    protected abstract void busMessage(EventBusMessage message);

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (unbinder!=null){
            unbinder.unbind();
            unbinder = null;
        }
        if (null != mRootView && mRootView.getParent()!=null) {
            ((ViewGroup) mRootView.getParent()).removeView(mRootView);
        }
    }
}
